#!/usr/bin/python
# -*- coding: utf-8 -*-


# cmap2owl -- Helper application to convert from concept maps to OWL ontologies
# Copyright (c) 2008-2013  Rodrigo Rizzi Starr
#  
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#  
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#  
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.


'''
This contains classes that are used to build the main interface

@author: Rodrigo Rizzi Starr
@copyright: Copyright © 2008-2013 Rodrigo Rizzi Starr
@license: MIT License
@contact: rodrigo.starr@gmail.com
'''


from log import log, configureStatisticsLogger
log.info('cmap2owl started')

import os
import sys

# GTK+ imports
import pygtk
if not sys.platform == 'win32':
    pygtk.require('2.0')
try:
    import gtk
    import gtk.glade
except Exception as e:
    from log import log
    log.error('gtk or gtk.glade module not found: %s, %s' % (e, dir(e)))
    sys.exit(1)

# Project imports
from prologWrapper import Prolog
from interface import CMapConverter
from lexiconEditor import LexiconEditor
from CXLReader import CXLReader
from mapper import Mapper
from log import log, statLog
from OWLSerializer import OWLSerializer

Prolog.logger = open('prolog.log', 'a')
Prolog.logger.write('\n\n\n**** Session started ****\n\n')

log.debug('Loaded...')

class BaseGUI(object):
    '''Standard application interface. Just a menu to open the c-maps
    '''
   
    # Methods called during initialization
    def __init__(self):
        
        # Sets up basic interface
        gladefile = "CMap2OWL-Interface.glade"
        windowname = "base"
        self.wTree = gtk.glade.XML(gladefile, windowname)
        self.win = self.wTree.get_widget(windowname)
        
        # Some menu option
        self.closeMenu = self.wTree.get_widget("close")
        self.saveMenu = self.wTree.get_widget("save")
        self.saveAsMenu = self.wTree.get_widget("save_as")
        
        dic = {"on_base_destroy" : self.exit,
               "on_open_activate" : self.open,
               "on_save_activate" : self.save,
               "on_close_activate" : self.close,
               "on_exit_activate" : self.exit,
               "on_portuguese_activate" : 
                    lambda widget: self.changeLanguage('pt'),
               "on_english_activate" : 
                    lambda widget: self.changeLanguage('en'),
               "on_lexiconEditor_activate" : self.lexiconEditor,
               "on_about_activate" : self.about,
               }

        self.wTree.signal_autoconnect(dic)
        
        # Placeholder for the main interface
        self.converter = None
        
        # The state manager
        self.state = BaseGUIState(self)
        
        # The open file
        self.filename = ''
        self.responseLogger = None
        
        # The default language
        self.changeLanguage('pt')
        
        # Shows the menu
        self.win.show()
    
    def exit(self, widget):
        "Exits the application"
        gtk.main_quit(widget)
    
    def open(self, widget):
        "Open a new concept map"
        chooser = gtk.FileChooserDialog(title = 'Choose a concept map',
                                        action = gtk.FILE_CHOOSER_ACTION_OPEN,
                                        buttons = (
                                         gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT,
                                         gtk.STOCK_OK, gtk.RESPONSE_ACCEPT)
                                        )
        fileFilter = gtk.FileFilter()
        fileFilter.add_pattern("*.cxl")
        chooser.add_filter(fileFilter)
        
        self.filename = ""
        answer = chooser.run()
        if answer == gtk.RESPONSE_ACCEPT:
            self.filename = chooser.get_filename()
        chooser.destroy()
        while gtk.events_pending():
            gtk.main_iteration_do()
        
        if self.filename != "":
            log.debug("Opening file: " + self.filename)

            # Creates the filename for the statistics logger
            i = 1
            loggerFilename = self.filename + '.%d.log'
            while os.path.exists(loggerFilename % i):
                i += 1
            configureStatisticsLogger(loggerFilename % i)
            log.info('Statistics log: ' + (loggerFilename % i))
            
            self.openCMap(self.filename)
    
    def openCMap(self, filename):
        "Opens a CMap for edition"
        
        self.filename = filename
        
        # Parses a certain CMap into a generic representation
        p = CXLReader(filename)
        
        p.parse()
        p.graph.redefineIdsFromLabels()
        p.graph.generatePhrases()

        # Recover some statistics from the concept map (a dictionary)
        statistics = p.graph.getStatistics()
        statisticsMessage = ', '.join(sorted('%s: %s' % datum 
                                      for datum in statistics.iteritems()))
        statLog.info('Concept map statistics: ' + statisticsMessage)
        
        # Now runs the Mapper to map the CMap into OWL
        mapper = Mapper(p, self.lexicon, self.tagger)
        mapper.map()
        
        # Creates a question logger
        nameGuess = os.path.splitext(self.filename)[0]
        i = 1
        while os.path.exists(nameGuess + '.' + str(i) + '.ruleLog'):
            i += 1
        name = nameGuess + '.' + str(i) + '.ruleLog'
        self.responseLogger = open(name, 'w')
        
        # Asks the questions
        self.converter = CMapConverter(self.wTree,
                                       mapper,
                                       self.win,
                                       self.responseLogger)
        
        # Change state
        self.state.setOpenMap(True)
        
    def save(self, widget):
        """Saves the current CMap"""
        # Now saves the mapper to an OWL file
        log.info("Saving: " + self.filename + ".owl")
        owltput = OWLSerializer(self.filename + ".owl", self.converter.mapper)
        owltput.serialize()
        self.converter.mapper.classifiers.save()
        self.responseLogger.flush()

    def close(self, widget):
        """Closes the current cmap"""
        # Now saves the mapper to an OWL file
        self.converter.close()
        self.state.setOpenMap(False)
        Prolog.clean()
        if self.responseLogger != None:
            self.responseLogger.close()

    def changeLanguage(self, language):
        """Changes the current language (both the lexicon and the tagger file)
        """
        self.lexicon = 'classifiers_%s.pickle' % language
        self.tagger = 'tagger_%s.pickle' % language

    def lexiconEditor(self, widget):
        """Edits the lexicon file"""
        
        # Creates an editor for the lexicon.
        editor = LexiconEditor(self.lexicon)
        editor.start()

    def about(self, widget):
        "Show an about dialog"
        about = gtk.AboutDialog()
        about.set_name("Conceptual map conversion")
        about.run()
        about.destroy()
        
    def start(self, fastOpen = ''):
        "Starts the application"
        
        if fastOpen != '':
            self.openCMap(fastOpen)
        gtk.main()

class BaseGUIState(object):
    """Manage the state of the base GUI
    """
   
    def __init__(self, baseGUI):
        self.baseGUI = baseGUI
        
        # State
        self.openMap = False
        self.unsaved = False
        
    def setOpenMap(self, value):
        "True if there is an open map"
        self.openMap = value
        self.baseGUI.closeMenu.set_sensitive(value)
        self.baseGUI.saveMenu.set_sensitive(value)
#        self.baseGUI.saveAsMenu.set_sensitive(value)
        
    def setUnsaved(self, value):
        "True if the current map has unsaved changes"
        self.unsaved = value
        self.baseGUI.saveMenu.set_sensitive(value)
        

if __name__ == "__main__":
    
    fOpen = ''
#    fOpen = '/home/rrs/Mestrado/ITA/Aquisicao/01/Trauma Encefalo-craniano.cxl'
#    fOpen = './test/Mapa simples.cxl'
#    fOpen = './test/mapas conceituais.cxl'
#    fOpen = './test/haveMap.cxl'
#    fOpen = '/home/rrs/Mestrado/ITA/Aquisicao/04/04 - Edgard.cxl'
#    fOpen = '/home/rrs/Mestrado/ITA/Aquisicao/12/12 - Juliana.cxl'
    
    application = BaseGUI()
    application.start(fOpen)
        
